// 创建一个进程

#include <func.h>
#include "head.h"
#include "worker.h"
int main(int argc, char *argv[])
{
    // 创建很多子进程

    ARGS_CHECK(argc, 4);
    int workerNUM = atoi(argv[3]);
    workerData_t *workerList = (workerData_t *)calloc(sizeof(workerData_t), workerNUM); // workerList 记录了所有工作进程的状态
    makeChild(workerList, workerNUM);

    // 初始化tcp连接
    int sockFd;
    int ret = tcpInit(&sockFd, argv[1], argv[2]);

    // 用epoll把tcp连接和子进程管理起来

    int epfd = epoll_create(1);
    epollAdd(sockFd, epfd);
    for (int i = 0; i < workerNUM; ++i)
    {
        epollAdd(workerList[i].pipeFd, epfd);
    }
    int listenSize = workerNUM + 1;
    struct epoll_event *readyArr = (struct epoll_event *)calloc(listenSize, sizeof(struct epoll_event)); 
    while (1)
    {
                                               
        int readyNum = epoll_wait(epfd, readyArr, listenSize, -1);
        printf("epoll_wait reafy!\n");
        for (int i = 0; i < readyNum; ++i)
        {
            if (readyArr[i].data.fd == sockFd)
            {
                puts("client connect");
                int netfd = accept(sockFd, NULL, NULL);
                ERROR_CHECK(netfd, -1, "accept");
                for (int j = 0; j < workerNUM; ++j)
                {
                    if (workerList[j].status == FREE)
                    {
                        printf("%d worker got a jib,pid = %d\n", j, workerList[j].pid);
                        sendFd(workerList[j].pipeFd, netfd);
                        close(netfd);
                        workerList[j].status = BUSY;
                        break;
                    }
                }
            }

            else
            {
                puts("one worker finisher his job");
                int j;
                for(j=0;j<workerNUM;j++)
                {
                    if(readyArr[i].data.fd==workerList[j].pipeFd)
                    {
                        pid_t pid;
                        int ret =read(workerList[j].pipeFd,&pid,sizeof(pid));
                        printf("%d worker finish his job ,pid = %d\n",j,pid);
                        workerList[j].status = FREE;
                           break;
                    }
                }
            }
        }
      }                                                          
}